"""
File: 08_发送邮件.py
Author: lvah
Date: 2020-01-14 
Connect: 976131979@qq.com
Description: 

"""

from datetime import datetime
import os
# 设置服务器,用户名、口令以及邮箱的后缀
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.utils import formataddr

"""
_subtype 指定要添加到 “Content-type:multipart/subtype”报头可选三种子类型
1. mixed 实现一个带附件的邮件体（默认的）
2. related 实现构建内嵌资源的邮件体
3. alternative 实现构建纯文本与超文本共存的邮件体
"""


smtp_server = "smtp.163.com"
from_username = '华为云技术中心'
mail_user = "15829216582@163.com"
# 是开启smtp的授权吗不是真实的密码。
mail_password = "python3"
# 邮件主题的前缀
mail_prefix = "[运维开发部]-"


def format_attach(file):
    """
    附件处理
    :param file: 文件对象
    :return:
    """
    filename = file.name
    base, ext = os.path.splitext(filename)
    attach = MIMEApplication(file.read(), _subtype=ext)
    attach.add_header('content-disposition', 'attachment', filename=filename)
    return attach


def send_email(to_addrs: str, subject: str, content: str, attaches=None):
    """
    发送邮件
    :param to_addrs: 邮件接收人
    :param subject: 邮件主题
    :param msg: 邮件正文内容
    :param attaches:
    :return: Bool
    """

    # 将要发送的文本信息做MIME封装
    # msg = MIMEText(content)
    msg = MIMEMultipart(_subtype='alternative')
    # 格式化发件人名称
    msg['From'] = formataddr([from_username, mail_user])
    msg['To'] = to_addrs
    msg['Subject'] = mail_prefix + subject
    # 邮件正文
    msg.attach(MIMEText(content))
    # 邮件附件
    if attaches:
        for attach in attaches:
            if os.path.exists(attach):
                with open(attach) as f:
                    msg.attach(format_attach(f))
            else:
                print("附件%s不存在" % (attach))
    try:
        """
        发件人邮箱中的SMTP服务器，一般端口是25。 常用的邮箱统计如下:
            邮箱名称    端口  SSL开启?  实例化代码
            QQ邮箱       465    True     smtplib.SMTP_SSL("smtp.qq.com",465)
            163邮箱       25    False    smtplib.SMTP()
        """

        # 1. 实例化smtp对象
        server = smtplib.SMTP()
        # 2. 连接邮件服务器
        server.connect(smtp_server)
        # 3. 登录
        server.login(mail_user, mail_password)
        # 4. 发送邮件内容
        server.sendmail(mail_user, to_addrs, msg.as_string())
        # 5. 关闭连接
        server.quit()
    except Exception as e:
        print(str(e))
        return False
    else:
        return True


if __name__ == '__main__':
    msg = "这里是报警内容，根据实际监控的情况加"
    to_list = '137965306@qq.com'
    now = str(datetime.now())
    result = send_email(to_list, "华为云技术中心" + now, msg, attaches=['hello.txt'])
    if result:
        print("发送成功.....")
    else:
        print("发送失败.....")
